//
//  ViewController+JSNative.m
//  AAPowerApp
//
//  Created by 李恺然 on 2018/11/26.
//  Copyright © 2018 Karl. All rights reserved.
//

#import "ViewController+JSNative.h"
#import "AppManager.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"

#define DEVICE_IS_IPAD (UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM())

@implementation ViewController (JSNative)

- (void)setupScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler webView:(WKWebView*)webView{
    WKUserContentController *userContentController = webView.configuration.userContentController;
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"logout"];
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"call_qrscan"];
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"call_local_qrscan"];
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"get_location"];
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"call_camera"];
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"call_mic"];
     [userContentController addScriptMessageHandler:scriptMessageHandler name:@"pop"];
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"logoutios"];
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"call_alert"];
    [userContentController addScriptMessageHandler:scriptMessageHandler name:@"call_toast"];

}

- (void)dealJSMethod:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"logout"]||
        [message.name isEqualToString:@"logoutios"]) {
        [[AppManager sharedManager] logoutWithCompetedHandler:NULL];
    }else if ([message.name isEqualToString:@"call_camera"]){
        [self call_cameraWithParams:message.body];
    }else if ([message.name isEqualToString:@"call_alert"]){
        [self call_alertWithParams:message.body];
    }else if ([message.name isEqualToString:@"call_toast"]){
        [self call_toastWithParams:message.body];
    }
}

- (void)call_alertWithParams:(NSDictionary *)params{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Notice" message:params[@"params"][@"text"] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:NULL];
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:NULL];
}

- (void)call_toastWithParams:(NSDictionary *)params{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.label.text = params[@"params"][@"text"];
    hud.mode = MBProgressHUDModeText;
    [hud hideAnimated:YES afterDelay:2.0];
}

- (void)call_cameraWithParams:(NSDictionary *)params{
    [AppManager sharedManager].tempUploadParams = params[@"params"];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Choose a photo" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *captureAction = [UIAlertAction actionWithTitle:@"Capture a photo" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self call_imagepicer_sourceType:UIImagePickerControllerSourceTypeCamera];
    }];
    
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"Take photo from album" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self call_imagepicer_sourceType:UIImagePickerControllerSourceTypePhotoLibrary];

    }];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:albumAction];
//    if (!DEVICE_IS_IPAD) {
        [alertVC addAction:captureAction];
//    }
    
    alertVC.popoverPresentationController.sourceView = [UIApplication sharedApplication].keyWindow.rootViewController.view;
    alertVC.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
}

- (void)call_imagepicer_sourceType:(UIImagePickerControllerSourceType)sourceType{
    
    if ([UIImagePickerController isSourceTypeAvailable:sourceType]) {
        NSLog(@"打开相册");
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        if (sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
            [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen; //调用本地相册，必须使用popover
           
        }else if(sourceType == UIImagePickerControllerSourceTypeCamera){
            [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
            imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen; 
        }
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }
//    else{
//        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//        hud.mode = MBProgressHUDModeText;
//        hud.label.text = @"";
//        [hud hideAnimated:YES afterDelay:2.0];
//    }
}

#pragma mark - ImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    [picker dismissViewControllerAnimated:YES completion:NULL];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self uploadImage:image params:[AppManager sharedManager].tempUploadParams];
}

- (void)uploadImage:(UIImage *)image params:(NSDictionary *)params{
    //加载到内存中，作为NSData对象
    NSData *data = UIImageJPEGRepresentation(image, 0.8);
    NSString *url = params[@"url"];
    NSString *name = [NSString stringWithFormat:@"%ld",[params[@"name"]integerValue]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    [manager POST:url parameters:@{@"name":name} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:data name:@"photo" fileName:[NSString stringWithFormat:@"%@.jpg",name] mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"progess %f",uploadProgress.fractionCompleted);
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
            NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            if ([result isEqualToString:@"1"]) {
                hud.label.text = @"Image upload success";
            }else{
                hud.label.text = @"Image upload failed";
            }
            hud.mode = MBProgressHUDModeText;
            [hud hideAnimated:YES afterDelay:2.0];
            [self.webView reload];
        });
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}


@end
